/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect, useMemo } from "react";
import { Modal, Form, InputNumber, message } from "antd";
import StandardTable from "@/components/StandardTable";

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const numberProps = { precision: 2, min: 0.01, max: 200 };

const EditWeightModal = props => {
  const { data, form, onClose, refreshPage, POST } = props;
  const { getFieldDecorator, validateFieldsAndScroll } = form;
  const [visible, setVisible] = useState(false);
  const [dataList, setDataList] = useState([]);
  const isSingle = !(dataList.length > 1);
  useEffect(
    () => {
      setVisible(!!data);
      if (data) {
        setDataList(
          data.map(({ waybill_no, id, charging_weight }) => ({ waybill_no, id, charging_weight }))
        );
        setVisible(true);
      } else {
        setDataList([]);
        setVisible(false);
      }
    },
    [data]
  );

  const handleOk = () => {
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        POST({
          type: "order_calculate/editList",
          payload: {
            data: JSON.stringify(
              data.map(({ waybill_no }) => ({
                waybill_no,
                charging_weight: values[`weight_${waybill_no}`],
              }))
            ),
          },
        }).then(() => {
          message.success("修改成功", 1);
          handleCancel();
          refreshPage();
        });
      } else {
        const msg = Object.values(error)[0].errors[0].message;
        if (!isSingle && msg) {
          message.error(msg);
        }
      }
    });
  };
  const handleCancel = () => {
    onClose(void 0);
  };

  const renderDefault = useMemo(
    () => (
      <div>
        <FormItem label="运单号">
          <span>{dataList[0]?.waybill_no}</span>
        </FormItem>
        <FormItem label="原重量">
          <span>{dataList[0]?.charging_weight ? `${dataList[0]?.charging_weight  }kg` : "暂无"}</span>
        </FormItem>
        <FormItem label="修改新重量">
          {getFieldDecorator(`weight_${dataList[0]?.waybill_no}`, {
            rules: [{ required: true, message: "请输入修改后的重量" }],
          })(
            <InputNumber placeholder="输入修改后的重量" style={{ width: "70%" }} {...numberProps} />
          )}
          <span style={{ marginLeft: 10 }}>kg</span>
        </FormItem>
      </div>
    ),
    [dataList, form]
  );

  const columns = useMemo(
    () => [
      {
        title: "运单号",
        dataIndex: "waybill_no",
        key: "waybill_no",
        align: "center",
        width:'30%',
      },
      {
        title: "原重量",
        dataIndex: "charging_weight",
        key: "charging_weight",
        align: "center",
        render: val => <span>{val ? `${val  }kg` : "暂无"}</span>,
        width:'15%',
      },
      {
        title: "修改后的重量",
        dataIndex: "newWeight",
        key: "newWeight",
        align: "center",
        render: (val, recode) => (
          <>
            {getFieldDecorator(`weight_${recode.waybill_no}`, {
              rules: [{ required: true, message: `请输入运单号为 ${recode.waybill_no} 修改后的重量` }],
            })(
              <InputNumber
                placeholder="输入修改后的重量"
                style={{ width: "70%" }}
                {...numberProps}
              />
            )}
            <span style={{ marginLeft: 10 }}>kg</span>
          </>
        ),
      },
    ],
    [form]
  );

  const renderTable = useMemo(
    () => (
      <div>
        <StandardTable
          rowKey={record => record.id}
          columns={columns}
          data={{ list: dataList }}
          scroll={{ y: 540 }}
        />
      </div>
    ),
    [dataList, form]
  );

  return (
    <Modal
      title="修改重量"
      centered
      visible={visible}
      onCancel={handleCancel}
      maskClosable
      onOk={handleOk}
      destroyOnClose
      width={isSingle ? 500 : 700}
    >
      {!!dataList.length && (
        <Form {...(isSingle ? formItemLayout : {})}>{isSingle ? renderDefault : renderTable}</Form>
      )}
    </Modal>
  );
};

export default Form.create()(EditWeightModal);
